/*
 * @Description: 同分组调序弹窗
 * @Author: Zzt
 * @Date: 2022-11-01 09:58:54
 * @LastEditTime: 2022-11-04 12:03:48
 */
import { Button, Col, Form, Input, Modal, Row, Select, Space, Table } from 'antd';
import Column from 'antd/es/table/Column';
import update from 'immutability-helper';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { DndProvider, useDrag, useDrop } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { CloseOutlined, PlusOutlined } from '@ant-design/icons';
import { Option } from 'antd/lib/mentions';
import { toNumber } from 'lodash-es';
import { isNullObj } from '@/utils';
import { useLevelTableContext } from '../../contexts/LevelTableContext';

interface DraggableBodyRowProps extends React.HTMLAttributes<HTMLTableRowElement> {
  index: number;
  moveRow: (dragIndex: number, hoverIndex: number) => void;
}
const type = 'DraggableBodyRow';
const DraggableBodyRow = ({
  index,
  moveRow,
  className,
  style,
  ...restProps
}: DraggableBodyRowProps) => {
  const ref = useRef<HTMLTableRowElement>(null);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: type,
    collect: (monitor) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward'
      };
    },
    drop: (item: { index: number }) => {
      moveRow(item.index, index);
    }
  });
  const [, drag] = useDrag({
    type,
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  });
  drop(drag(ref));
  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};
const GroupReorderDialog = (props: any) => {
  const [form] = Form.useForm();
  const { visible, onClose } = props;
  const { getGroupList, baseInfo, selectItems, groupList } = useLevelTableContext();

  const [data, setData] = useState([]);
  const [input, setInput] = useState('');
  const [orderVisible, setOrderVisible] = useState(false);
  const [sortValue, setSortValue] = useState('0');
  // 表格选中的项目
  const [selectItem, setSelectKey] = useState([]);
  const [loading, setLoading] = useState(false);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  const [total, setTotal] = useState(0);

  /* 切换页码查找列表 */
  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);
      getGroupList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
          setData(res);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);
  useEffect(() => {
    if (visible) {
      setListQuery((state: any) => ({
        ...state,
        param: {
          atCode: baseInfo.atCode,
          atType: baseInfo.atType,
          commonParams: { dbName: baseInfo.dbName },
          level: baseInfo.level,
          entryId: selectItems[0]
        }
      }));
    }
  }, [visible]);
  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };
  const moveRow = useCallback(
    (dragIndex: number, hoverIndex: number) => {
      const dragRow = data[dragIndex];
      setData(
        update(data, {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragRow]
          ]
        })
      );
    },
    [data]
  );

  const components = {
    body: {
      row: DraggableBodyRow
    }
  };
  const regularOrder = () => {
    setOrderVisible(true);
  };

  const onFinish = (values: any) => {
    console.log('Received values of form:', values);
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };
  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItem,
    onChange: onSelectChange
  };

  /* GO调序 */
  const moveSelect = () => {
    if (selectItem[0] + 1 < toNumber(input)) {
      const changed = data.slice(selectItem[0], toNumber(input));
      setData((state) =>
        state
          .slice(0, selectItem[0])
          .concat(changed.slice(1).concat(changed[0]))
          .concat(state.slice(toNumber(input)))
      );
    } else if (selectItem[0] + 1 > toNumber(input)) {
      const changed = data.slice(toNumber(input) - 1, selectItem[0] + 1);
      setData((state) =>
        state
          .slice(0, toNumber(input) - 1)
          .concat(
            [state[selectItem[0]]]
              .concat(changed.slice(0, selectItem[0] - toNumber(input) + 1))
              .concat(state.slice(selectItem[0] + 1))
          )
      );
    } else {
      console.log('无需调整');
    }
  };
  return (
    <>
      <Modal title="同分组调序" visible={visible} onCancel={onClose} width={800} destroyOnClose>
        <Space style={{ display: 'flex', marginBottom: 8 }} direction="vertical">
          <p>调整同分组档案顺序，完成后点击更新序号。</p>
          <Row>
            <Col span={11}>鼠标拖动选中行可调整行的顺序，或者将选中行移至第</Col>
            <Col span={2}>
              <Input onChange={(event) => setInput(event.target.value)} />
            </Col>
            <Col>
              <Button type="text">行</Button>
            </Col>
            <Col span={6}>
              <Button onClick={moveSelect}>GO</Button>
            </Col>
            <Col>
              <Button type="link" onClick={regularOrder}>
                按规则调序
              </Button>
            </Col>
          </Row>
          <DndProvider backend={HTML5Backend}>
            <Table
              size="small"
              components={components}
              dataSource={data}
              bordered
              rowKey={(_, index) => {
                return index;
              }}
              onRow={(_, index) => {
                const attr = {
                  index,
                  moveRow
                };
                return attr as React.HTMLAttributes<any>;
              }}
              pagination={{
                current: listQuery.pageNo,
                pageSize: listQuery.pageSize,
                total,
                onChange: pageChange
              }}
              rowSelection={{ type: 'radio', ...rowSelection }}
            >
              <Column title="卷内序号" key={'id'} dataIndex="id" />
              <Column title="题名" key={'title'} dataIndex="title" />
              <Column title="分类号" key={'classno'} dataIndex="classno" />
              <Column title="年度" key={'year'} dataIndex="year" />
              <Column title="密级" key={'securitycls'} dataIndex="securitycls" />
              <Column title="保管期限" key={'retentionprd'} dataIndex="retentionprd" />
            </Table>
          </DndProvider>
        </Space>
      </Modal>
      <Modal
        closable={false}
        visible={orderVisible}
        onCancel={() => setOrderVisible(false)}
        footer={[
          <Button onClick={() => form.resetFields()} key="clear">
            清空
          </Button>,
          <Button onClick={() => setOrderVisible(false)} key="cancel">
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={() => form.submit()}>
            确认
          </Button>
        ]}
      >
        <Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off" form={form}>
          <Form.List name="sortField">
            {(fields, { add, remove }) => (
              <>
                <Form.Item label="添加排序字段" colon={false}>
                  <Button type="link" onClick={() => add()}>
                    添加一行
                  </Button>
                </Form.Item>
                {fields.map(({ key, name, ...restField }) => (
                  <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                    <Form.Item {...restField} name={[name, 'fields']}>
                      <Select style={{ width: 240 }} placeholder="=请选择排序字段=">
                        <Select.Option value="0">升序</Select.Option>
                        <Select.Option value="1">降序</Select.Option>
                      </Select>
                    </Form.Item>
                    <Form.Item {...restField} name={[name, 'sort']}>
                      <Select
                        style={{ width: 70 }}
                        value={sortValue}
                        onChange={(value) => setSortValue(value)}
                      >
                        <Select.Option value="0">升序</Select.Option>
                        <Select.Option value="1">降序</Select.Option>
                      </Select>
                    </Form.Item>
                    <CloseOutlined onClick={() => remove(name)} />
                  </Space>
                ))}
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </>
  );
};
export default GroupReorderDialog;
